<?php
// +----------------------------------------------------------------------
// | 销售人员信息表
// +----------------------------------------------------------------------
// | Author: cart <469714167@qq.com>
// +----------------------------------------------------------------------
// | Datetime: 2017-12-10 09:00:00
// +----------------------------------------------------------------------
// | Copyright: ShunLuZhiDi
// +----------------------------------------------------------------------
namespace app\shop\model;
use think\Db;
use think\Model;
use org\BaiduMap;

class Index extends Model
{
    /**
     * 查看类型列表
     * @param  [int]    $level      [等级]
     * @return [array]  $data       [商户数据]
     */
    public function getCategoryData($level)
    {
        $data = $this->table('slzd_sh_goods_category')
            ->where('is_show',1)
            ->where('level',$level)
            ->order('sort_order desc')
            ->select();
        if($data){
            foreach($data as &$v){
                if($v['image']){
                    $v['image'] = config('shopimg').$v['image'];
                }else{
                    $v['image'] = config('shopimg').'/public/upload/12381514956316.jpg';
                }
            }
        }
        return $data;
    }

    //获取标签数据
    public function getTitleData()
    {
        $data = $this->table('slzd_sh_goods_label')
            ->where('is_show',1)
            ->order('sort desc')
            ->select();
        if($data){
            foreach($data as &$v){
                if($v['image']){
                    $v['image'] = config('shopimg').$v['image'];
                }else{
                    $v['image'] = config('shopimg').'/public/upload/12381514956316.jpg';
                }
            }
        }
        return $data;
    }

    // 查看首页详情
    public function getNearbySellerData($data,$page,$orll_page)
    {
        $shIds = [];
        $radius = config('radius');
        $coordinate['lng'] = $data['lng'];
        $coordinate['lat'] = $data['lat'];
        $nearSh = nearCoordinate(config('mongodbConf.host'),'slzd_pro',config('mongodbConf.seller'),$coordinate,$radius)['results'];
        foreach ($nearSh as $key => $value) {
            $shIds[] = $value['obj']['id'];
        }
        $seller_list['row'] = $this->table('slzd_sh_admin a')
            ->join('slzd_rrb_list b','a.category_id = b.id')
            ->join('slzd_sh_goods_category c','a.admin_id = c.seller_id')
            ->join('slzd_sh_goods d','d.cat_id = c.id')
            ->field('admin_id,a.category_id,lat,lng,shop_name,shop_logo,a.label,start_fee,freight,base_freight,is_order,o_start_time,o_end_time,b.name')
            ->where('audit',1)
            ->where('a.status',1)
            ->where('admin_id','in',$shIds)
            ->page($page,$orll_page)
            ->group('a.admin_id')
            ->select();
        $total = $this->table('slzd_sh_admin a')
            ->join('slzd_rrb_list b','a.category_id = b.id')
            ->where('audit',1)
            ->where('a.status',1)
            ->where('admin_id','in',$shIds)
            ->group('a.admin_id')
            ->count();
        $seller_list['count'] = ceil($total/$orll_page);
        $seller_list['page'] = $page;
        foreach($seller_list['row'] as $key => &$value){
            if($value['shop_logo']){
                $value['shop_logo'] = config('shopimg').$value['shop_logo'];
            }else{
                $value['shop_logo'] =  config('shopimg').'/public/upload/12381514956316.jpg';
            }
            $value['o_start_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_start_time']));
            $value['o_end_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_end_time']));
            if(time() > $value['o_start_time'] && time() < $value['o_end_time'] && $value['is_order'] == 1){
                $value['is_server'] = 1;
            }elseif($value['is_order'] == 0){
                $value['is_server'] = 2;
            }else{
                $value['is_server'] = 3;
            }
            $sql = "select count(*) count from slzd_sh_order where seller_id = {$value['admin_id']} group by MONTH(confirm_time) limit 1";
            $value['sum'] = db::query($sql);
            if(count($value['sum']) > 0){
                $value['sales_sum'] = $value['sum'][0]['count'];
            }else{
                $value['sales_sum'] = 0;
            }
            $baidu = new BaiduMap();
            $value['end_kilometers'] = $baidu::getDistanceInfo2($data['lng'], $data['lat'], $value['lng'], $value['lat']);
            if(!$value['base_freight']){
                $value['show_base_freight'] = '免基础运费';
            }else{
                $value['show_base_freight'] = '基础运费'.($value['base_freight']/100).'元';
            }
            $value['show_start_fee'] = ($value['start_fee']/100).'元起送';
            $value['show_end_kilometers'] = $value['end_kilometers'][0]['distance']['text'];
            $value['show_kilometers_time'] = $value['end_kilometers'][0]['duration']['text'];
            $value['kilometers'] = $value['end_kilometers'][0]['duration']['value'];
            unset($value['end_kilometers']);
        }
        array_multisort(array_column($seller_list['row'],'sales_sum'),SORT_DESC,$seller_list['row']);
        unset($key,$value);
        return $seller_list;
    }

    // 查看首页详情
    public function getSearchSellerData($data,$page,$orll_page)
    {
        $shIds = [];
        $radius = config('radius');
        $coordinate['lng'] = $data['lng'];
        $coordinate['lat'] = $data['lat'];
        $nearSh = nearCoordinate(config('mongodbConf.host'),'slzd_pro',config('mongodbConf.seller'),$coordinate,$radius)['results'];
        foreach ($nearSh as $key => $value) {
            $shIds[] = $value['obj']['id'];
        }
        if(!$data['keyWord']){
            $data['keyWord'] = ' ';
        }
        $seller_list['row'] = $this->table('slzd_sh_admin a')
            ->join('slzd_rrb_list b','a.category_id = b.id')
            ->join('slzd_sh_goods c','a.admin_id = c.seller_id')
            ->field('admin_id,a.category_id,lat,lng,shop_name,shop_logo,a.label,start_fee,freight,base_freight,is_order,o_start_time,o_end_time,b.name')
            ->where('audit',1)
            ->where('a.status',1)
            ->where('admin_id','in',$shIds)
            ->where('shop_name|goods_name','like','%'.$data['keyWord'].'%')
            ->page($page,$orll_page)
            ->group('admin_id')
            ->select();
        // echo $this->getLastSql();exit;
        $total = $this->table('slzd_sh_admin a')
            ->join('slzd_rrb_list b','a.category_id = b.id')
            ->join('slzd_sh_goods c','a.admin_id = c.seller_id')
            ->where('audit',1)
            ->where('a.status',1)
            ->where('admin_id','in',$shIds)
            ->where('shop_name|goods_name','like','%'.$data['keyWord'].'%')
            ->page($page,$orll_page)
            ->group('admin_id')
            ->count();
        $seller_list['count'] = ceil($total/$orll_page);
        $seller_list['page'] = $page;
        foreach($seller_list['row'] as $key => &$value){
            if($value['shop_logo']){
                $value['shop_logo'] = config('shopimg').$value['shop_logo'];
            }else{
                $value['shop_logo'] =  config('shopimg').'/public/upload/12381514956316.jpg';
            }
            $value['o_start_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_start_time']));
            $value['o_end_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_end_time']));
            if(time() > $value['o_start_time'] && time() < $value['o_end_time'] && $value['is_order'] == 1){
                $value['is_server'] = 1;
            }elseif($value['is_order'] == 0){
                $value['is_server'] = 2;
            }else{
                $value['is_server'] = 3;
            }
            $sql = "select count(*) count from slzd_sh_order where seller_id = {$value['admin_id']} group by MONTH(confirm_time) limit 1";
            $value['sum'] = db::query($sql);
            if(count($value['sum']) > 0){
                $value['sales_sum'] = $value['sum'][0]['count'];
            }else{
                $value['sales_sum'] = 0;
            }
            $baidu = new BaiduMap();
            $value['end_kilometers'] = $baidu::getDistanceInfo2($data['lng'], $data['lat'], $value['lng'], $value['lat']);
            if(!$value['base_freight']){
                $value['show_base_freight'] = '免基础运费';
            }else{
                $value['show_base_freight'] = '基础运费'.($value['base_freight']/100).'元';
            }
            $value['show_start_fee'] = ($value['start_fee']/100).'元起送';
            $value['show_end_kilometers'] = $value['end_kilometers'][0]['distance']['text'];
            $value['show_kilometers_time'] = $value['end_kilometers'][0]['duration']['text'];
            $value['kilometers'] = $value['end_kilometers'][0]['duration']['value'];
            unset($value['end_kilometers']);
        }
        unset($key,$value);
        // dump($);
        if($data['sort'] == 1){
            array_multisort(array_column($seller_list['row'],'sales_sum'),SORT_DESC,$seller_list['row']);
        }else{
            array_multisort(array_column($seller_list['row'],'kilometers'),SORT_ASC,$seller_list['row']);
        }
        return $seller_list;
    }
    public function getSellerDetail($seller_id){
        $data = $this->table('slzd_sh_admin a')
        ->where('admin_id',$seller_id)
        ->find();
        return $data;
    }
    //获取主分类的商户
    public function getCategoryListData($data,$page,$orll_page){
        $shIds = [];
        $radius = config('radius');
        $coordinate['lng'] = $data['lng'];
        $coordinate['lat'] = $data['lat'];
        $nearSh = nearCoordinate(config('mongodbConf.host'),'slzd_pro',config('mongodbConf.seller'),$coordinate,$radius)['results'];
        foreach ($nearSh as $key => $value) {
            $shIds[] = $value['obj']['id'];
        }
        $seller_list['row'] = $this->table('slzd_sh_admin a')
            ->join('slzd_rrb_list b','a.category_id = b.id')
            ->join('slzd_sh_goods_category c','a.admin_id = c.seller_id')
            ->join('slzd_sh_goods d','d.cat_id = c.id')
            ->field('admin_id,a.category_id,lat,lng,shop_name,shop_logo,a.label,start_fee,freight,base_freight,is_order,o_start_time,o_end_time,b.name')
            ->where('audit',1)
            ->where('a.status',1)
            ->where('admin_id','in',$shIds)
            ->where('a.category_id',$data['category_id'])
            ->page($page,$orll_page)
            ->group('a.admin_id')
            ->select();
            // echo $this->getLastSql();exit;
        $total = $this->table('slzd_sh_admin a')
            ->join('slzd_rrb_list b','a.category_id = b.id')
            ->join('slzd_sh_goods_category c','a.admin_id = c.seller_id')
            ->join('slzd_sh_goods d','d.cat_id = c.id')
            ->where('audit',1)
            ->where('a.status',1)
            ->where('admin_id','in',$shIds)
            ->where('a.category_id',$data['category_id'])
            ->group('a.admin_id')
            ->count();
        $seller_list['count'] = ceil($total/$orll_page);
        $seller_list['page'] = $page;
        foreach($seller_list['row'] as $key => &$value){
            if($value['shop_logo']){
                $value['shop_logo'] = config('shopimg').$value['shop_logo'];
            }else{
                $value['shop_logo'] =  config('shopimg').'/public/upload/12381514956316.jpg';
            }
            $value['o_start_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_start_time']));
            $value['o_end_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_end_time']));
            if(time() > $value['o_start_time'] && time() < $value['o_end_time'] && $value['is_order'] == 1){
                $value['is_server'] = 1;
            }elseif($value['is_order'] == 0){
                $value['is_server'] = 2;
            }else{
                $value['is_server'] = 3;
            }
            $sql = "select count(*) count from slzd_sh_order where seller_id = {$value['admin_id']} group by MONTH(confirm_time) limit 1";
            $value['sum'] = db::query($sql);
            if(count($value['sum']) > 0){
                $value['sales_sum'] = $value['sum'][0]['count'];
            }else{
                $value['sales_sum'] = 0;
            }
            if(!$value['base_freight']){
                    $value['show_base_freight'] = '免基础运费';
                }else{
                    $value['show_base_freight'] = '基础运费'.($value['base_freight']/100).'元';
                }
            $value['show_start_fee'] = ($value['start_fee']/100).'元起送';
            $baidu = new BaiduMap();
            $value['end_kilometers'] = $baidu::getDistanceInfo2($data['lng'], $data['lat'], $value['lng'], $value['lat']);
            $value['show_end_kilometers'] = $value['end_kilometers'][0]['distance']['text'];
            $value['show_kilometers_time'] = $value['end_kilometers'][0]['duration']['text'];
            $value['kilometers'] = $value['end_kilometers'][0]['duration']['value'];
        }
        unset($key,$value);
        if($data['sort'] == 1){
            array_multisort(array_column($seller_list['row'],'sales_sum'),SORT_DESC,$seller_list['row']);
        }else{
            array_multisort(array_column($seller_list['row'],'kilometers'),SORT_ASC,$seller_list['row']);
        }
        return $seller_list;
    }
    //获取标签的商户
    public function getLabelListData($data,$page,$orll_page){
        $i = config('distance'); //差值可自定义，值越大，范围就越大
        $min_latitude = $data['lat'] - $i; //纬度最小值
        $max_latitude = $data['lat'] + $i; //纬度最大值
        $min_longitude = $data['lng'] - $i; //经度最小值
        $max_longitude = $data['lng'] + $i; //经度最大值
        $seller_list['row'] = $this->table('slzd_sh_admin')
            ->field('admin_id,category_id,lat,lng,shop_name,shop_logo,label,start_fee,freight,base_freight,is_order,o_start_time,o_end_time')
            ->where('lat','between',[$min_latitude,$max_latitude])
            ->where('lng','between',[$min_longitude,$max_longitude])
            ->where('audit',1)
            ->where('a.status',1)
            ->where('label',$data['label_id'])
            ->page($page,$orll_page)
            ->select();
        $total = Db::table('slzd_sh_admin a')
            ->where('lat','between',[$min_latitude,$max_latitude])
            ->where('lng','between',[$min_longitude,$max_longitude])
            ->where('audit',1)
            ->where('a.status',1)
            ->where('label',$data['label_id'])
            ->count();
        $seller_list['count'] = ceil($total/$orll_page);
        $seller_list['page'] = $page;
            foreach($seller_list['row'] as $key => &$value){
                if($value['shop_logo']){
                    $value['shop_logo'] = config('shopimg').$value['shop_logo'];
                }else{
                    $value['shop_logo'] =  config('shopimg').'/public/upload/12381514956316.jpg';
                }
                if($value['background_image']){
                    $value['background_image'] = config('shopimg').$value['background_image'];
                }else{
                    $value['background_image'] =  config('shopimg').'/public/upload/3611538975826.jpg';
                }
                $value['o_start_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_start_time']));
                $value['o_end_time'] = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$value['o_end_time']));
                if(time() > $value['o_start_time'] && time() < $value['o_end_time'] && $value['is_order'] == 1){
                    $value['is_server'] = 1;
                }elseif($value['is_order'] == 0){
                    $value['is_server'] = 2;
                }else{
                    $value['is_server'] = 3;
                }
            $value['end_kilometers'] =  getDistanceBetweenPointsNew($data['lat'],$data['lng'],$value['lat'],$value['lng']);
                if(!$value['base_freight']){
                    $value['show_base_freight'] = '免基础运费';
                }else{
                    $value['show_base_freight'] = '基础运费'.$value['base_freight'].'元';
                }
            $value['show_start_fee'] = $value['start_fee'].'元起送';
            if(is_float($value['end_kilometers']['kilometers'])){
                $len = strpos($value['end_kilometers']['kilometers'],'.');
                $value['show_end_kilometers'] = '距离'.substr($value['end_kilometers']['kilometers'],0,($len+2)).'公里';
            }else{
                $value['show_end_kilometers'] = '距离'.$value['end_kilometers']['kilometers'].'公里';
            }
            $value['end_kilometers'] =  $value['end_kilometers']['kilometers'];
        }
        unset($key,$value);
        return $seller_list;
        // 获取商户列表
    }
    /**
     * [getSellerListData 商户详情]
     * @param  [array] $data [description]
     * @return [array]       [商户详情数据]
     */
    public function getSellerListData($data)
    {
        $list['seller'] = $this->table('slzd_sh_admin a')
        ->join('slzd_sh_auth b','a.admin_id = b.admin_id')
        ->join('slzd_rrb_list c','a.category_id = c.id')
        ->where('a.admin_id',$data['seller_id'])
        ->find();
        if($list['seller']['shop_logo']){
            $list['seller']['shop_logo'] = config('shopimg').$list['seller']['shop_logo'];
        }else{
            $list['seller']['shop_logo'] =  config('shopimg').'/public/upload/12381514956316.jpg';
        }
        if($list['seller']['background_image']){
            $list['seller']['background_image'] = config('shopimg').$list['seller']['background_image'];
        }else{
            $list['seller']['background_image'] =  config('shopimg').'/public/upload/3611538975826.jpg';
        }
        unset($list['seller']['salt']);
        unset($list['seller']['ec_salt']);
        $o_start_time = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$list['seller']['o_start_time']));
        $o_end_time = strtotime(date('Y-m-d',time()).' '.date('H:i:s',$list['seller']['o_end_time']));
        if(time() > $o_start_time && time() < $o_end_time && $list['seller']['is_order'] == 1){
            $list['seller']['is_server'] = 1;
        }elseif($list['seller']['is_order'] == 0){
            $list['seller']['is_server'] = 2;
        }else{
            $list['seller']['is_server'] = 3;
        }

        $category1 = $this->table('slzd_sh_goods a')
            ->join('slzd_sh_goods_category b','a.cat_id = b.id')
            ->field('b.id,b.parent_id,b.name')
            ->order('sort_order desc','b.is_hot desc')
            ->where('b.is_show',1)
            ->where('b.is_hot',1)
            ->where('a.seller_id',$list['seller']->admin_id)
            ->group('b.id')
            ->select();
        $category = $this->table('slzd_sh_admin a')
            ->join('slzd_sh_goods_category b','a.admin_id = b.seller_id')
            ->field('b.name,b.id,b.parent_id')
            ->order('id')
            ->where('b.is_show',1)
            ->where('b.is_hot',1)
            ->where('a.admin_id',$list['seller']->admin_id)
            ->select();
        $parent_category =  $this->table('slzd_sh_goods_category a')
            ->field('name,id,parent_id')->order('id')
            ->where('id',$list['seller']->category_id)
            ->find();

        $goods_list = $this->table('slzd_sh_goods_category b')
        ->join('slzd_sh_goods c','c.cat_id = b.id')
        ->where('c.seller_id',$list['seller']->admin_id)
        ->where('is_on_sale',1)
        ->order('sort desc','goods_hot desc')
        ->column('cat_id');
        $goods_list = array_unique($goods_list);
        if(!in_array($parent_category['id'], $goods_list)){
            $marking = 1;
        }else{
            array_unshift($category1,$parent_category);
            $marking = 0;
        }
        $list['seller']['sales_sum'] = $this->table('slzd_sh_order')
            ->where('seller_id',$list['seller']['admin_id'])
            ->count();
        if(!$list['seller']['base_freight']){
            $list['seller']['show_base_freight'] = '免基础运费';
        }else{
            $list['seller']['show_base_freight'] = '基础运费'.($list['seller']['base_freight']/100).'元';
        }
        $list['seller']['show_start_fee'] = ($list['seller']['start_fee']/100).'元起送';
        $baidu = new BaiduMap();
        $list['seller']['end_kilometers'] = $baidu::getDistanceInfo2($data['lng'], $data['lat'], $list['seller']['lng'], $list['seller']['lat']);
        $list['seller']['show_end_kilometers'] = $list['seller']['end_kilometers'][0]['distance']['text'];
        $list['seller']['show_kilometers_time'] = $list['seller']['end_kilometers'][0]['duration']['text'];
        unset($list['seller']['end_kilometers']);
        //商户标题
        $seller_data['title'] = $list['seller'];
        if($marking){
            $seller_data['category'] = getSellerTreeData($category1,$list['seller']['category_id']);
        }else{
            $seller_data['category'] = getSellerTreeData($category1);
        }
        
        //活动
        // $now_time = time();
        // $where = " start_time <= $now_time and end_time >= $now_time ";
        // $where .= " and seller_id = {$data['seller_id']} ";
        // $list = Db::name('sh_prom_goods')
        // ->field('id,start_time,end_time,type')
        // ->where($where)->select();
        // foreach ($list as &$value) {
        //     switch ($value['type']) {
        //         case 0:
        //             $value['name'] =  '打折';
        //             break;
        //         case 1:
        //             $value['name'] =  '秒杀';
        //             break;
        //         case 2:
        //             $value['name'] =  '直降';
        //             break;
        //         case 3:
        //             $value['name'] =  '买就赠代金券';
        //             break;
        //     }
        //     $value['prom_type'] = 1;
        // }
        //商品促销   保留
        // if($seller_data){
        //     $prom = ['name'=>'单品优惠','id'=>0,'prom_type'=>1,'children'=>$list];
        //     array_unshift($seller_data,$prom);
        // }
        //
        //单个父类   测试
        // $seller_data = $this->table('tp_admin a')
        //     ->join('tp_goods_category b','a.category_id = b.parent_id')
        //     // ->join('tp_goods c','c.cat_id = b.id')
        //     ->field('b.*,admin_id,category_id,lat,lng,shop_name,shop_logo,label,start_fee,freight,base_freight,seller_id')
        //     ->where(function ($query) use ( $data ) {
        // $query->where('parent_id',$data['categoryId']);
        //     })->where(function ($query) use ( $data ) {
        //         $query->where('seller_id',$data['sellerId'])->whereor('seller_id',0);
        //     })->select();
        //该商店所有商品
        // $seller_data = $this->table('tp_admin a')
        //     ->join('tp_goods_category b','a.category_id = b.parent_id')
        //     ->join('tp_goods c','c.cat_id = b.id')
        //     ->field('b.*,c.*,admin_id,category_id,lat,lng,shop_name,shop_logo,label,start_fee,freight,base_freight')
        //     ->where('parent_id',$data['categoryId'])
        //     ->where('parent_id',$data['sellerId'])
        //     ->select();

        //     foreach($seller_data as $key => &$value){
        //     $value['end_kilometers'] =  getDistanceBetweenPointsNew($data['lat'],$data['lng'],$value['lat'],$value['lng']);
        //         if(!$value['base_freight']){
        //             $value['show_base_freight'] = '免基础运费';
        //         }else{
        //             $value['show_base_freight'] = '基础运费'.$value['base_freight'].'元';
        //         }
        //     $value['show_start_fee'] = $value['start_fee'].'元起送';
        //     if(is_float($value['end_kilometers']['kilometers'])){
        //         $len = strpos($value['end_kilometers']['kilometers'],'.');
        //         $value['show_end_kilometers'] = '距离'.substr($value['end_kilometers']['kilometers'],0,($len+2)).'公里';
        //     }else{
        //         $value['show_end_kilometers'] = '距离'.$value['end_kilometers']['kilometers'].'公里';
        //     }
        //     $value['end_kilometers'] =  $value['end_kilometers']['kilometers'];
        // }

        unset($key,$value);
        return $seller_data;
    }
}